/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs.web;

import org.gtugs.domain.Chapter;
import org.gtugs.domain.User;
import org.gtugs.service.ChapterManager;
import org.gtugs.service.CountryManager;
import org.gtugs.service.security.AppEngineUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jasonacooper@google.com (Jason Cooper)
 */
public class AddChapterFormController extends SimpleFormController {

  @Autowired	
  private ChapterManager chapterManager;
  @Autowired
  private CountryManager countryManager;

  @Override 
  protected void initBinder(HttpServletRequest request,
      ServletRequestDataBinder binder) throws Exception {
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
  }

  @Override
  @SuppressWarnings("unchecked")
  protected ModelAndView showForm(HttpServletRequest request,
      HttpServletResponse response, BindException errors) {
    Map<String, Object> map = new HashMap<String, Object>();
    Map model = errors.getModel();

    AppEngineUserService userService = new AppEngineUserService();
    map.put("userService", userService);
    model.put("model", map);

    if (!hasAccess(userService)) {
      userService.setAfterLogoutEndpoint("/admin");

      String errorText = "This page is restricted to site administrators. " +
          "Please sign in again with an administrator account to access " +
          "this page.";
      model.put("errorText", errorText);

      return new ModelAndView("admin_error", model);
    }

    map.put("countries", countryManager.getCountries());

    return new ModelAndView(getFormView(), model);
  }

  @Override
  protected Object formBackingObject(HttpServletRequest request) throws
      ServletException {
    Chapter chapter = new Chapter();
    chapter.getAdministrators().add(new User());

    return chapter;
  }

  @Override
  public ModelAndView onSubmit(Object command) throws ServletException {
    AppEngineUserService userService = new AppEngineUserService();

    if (!hasAccess(userService)) {
      String errorText = "This page is restricted to site administrators. " +
          "Please sign in again with an administrator account to access " +
          "this page.";

      return new ModelAndView("error", "errorText", errorText);
    }

    Chapter chapter = (Chapter) command;
    chapter.setCreatedOn(new Date());
    chapterManager.storeChapter(chapter);

    return new ModelAndView(new RedirectView(getSuccessView()));
  }

  public void setChapterManager(ChapterManager chapterManager) {
    this.chapterManager = chapterManager;
  }

  public void setCountryManager(CountryManager countryManager) {
    this.countryManager = countryManager;
  }

  private boolean hasAccess(AppEngineUserService userService) {
    return userService.isUserAdmin();
  }
}
